package org.yaglyf.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.yaglyf.common.FastJsonRedisSerializer;
import org.yaglyf.common.StringSerializer;

/**
 * @author
 * @version 1.0.0
 * @date 16/4/15 下午3:19.
 * @blog
 */
@Configuration
public class RedisConfig {
//
    private static final Long TIMEOUT = 1000*30*15L;
    @Bean
    public CacheManager cacheManager(@Qualifier("redisTemplate") RedisTemplate template) {
        RedisCacheManager manager = new RedisCacheManager(template);
        manager.setDefaultExpiration(TIMEOUT);
        return manager;
    }

//    @Bean
//    public StringRedisTemplate redisTemplate(RedisConnectionFactory factory) {
//        StringRedisTemplate template = new StringRedisTemplate(factory);
//        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//        ObjectMapper om = new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        jackson2JsonRedisSerializer.setObjectMapper(om);
//        template.setValueSerializer(jackson2JsonRedisSerializer);
//        template.afterPropertiesSet();
//        return template;
//    }
//
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }
//
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new StringSerializer());
        template.setValueSerializer(new FastJsonRedisSerializer<Object>());
        template.setHashKeySerializer(new StringSerializer());
        template.setHashValueSerializer(new FastJsonRedisSerializer<Object>());
        //template.expire();
        return template;
    }


}
